package data_structure.array;

/**
 * Created by l19743 on 2020/12/1.
 */
public class ArrayTest {
    public static void main(String[] args) {
        int[] nums = {1, 0, 0, 0, 4};
        splitByParticularNum(nums);
        for (int num : nums) {

            System.out.println(num);
        }
    }

    /**
     * 不变动数组的相对位置，将满足元素的数组整体往左平移
     * ex：将补位0的数组元素整体往左进行平移
     */

    public static void shift2Left(int[] nums) {
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[j++] = nums[i];
            }
        }

        for (int i = j; i < nums.length; i++) {
            nums[i] = 0;
        }
    }

    /**
     * 将数组以一个满足条件的元素进行分隔，满足条件的在左边反之右边
     * ex：以0为元素进行分隔，不为0的在数组左边，为0的在数组右边
     */
    public static void splitByParticularNum(int[] nums) {
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                ++j;
            }
        }
    }

    /**
     * leetcode 26
     * 原地消除数组中指定的元素
     */
    public static int removeElement(int[] nums, int val) {
        if (null == nums || nums.length == 0) return 0;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[count++] = nums[i];
            }
        }

        return count;
    }

    /**
     * leetcode 27
     * 原地删除数组中重复的元素
     */
    public static int removeDuplicates(int[] nums) {
        if (null == nums || nums.length == 0) return 0;
        int i = 0, j = 1;
        for (; j < nums.length; ) {
            if ((nums[i] ^ nums[j]) == 0) {
                ++j;
            } else {
                ++i;
                nums[i] = nums[j];
                ++j;
            }
        }
        return ++i;
    }

    /**
     * 获取数组中的最长子串的结果
     */
    public static int maxSubArray(int[] nums) {
        int sum = 0;
        int res = nums[0];//存储每一次的最优结果，每次的最优最后推到结果的最优
        for (int i = 0; i < nums.length; i++) {
            if (sum > 0) {
                sum += nums[i];
            } else {
                sum = nums[i];
            }
            res  = Math.max(res, sum);
        }
        return res;
    }


    /**
     * 数组左右互换的方法，
     * */
    public static void exchange(int[] nums) {
        int i = 0, j = nums.length - 1;
        while (i < j) {
            nums[i] = (char) (nums[i] + nums[j]);
            nums[j] = (char) (nums[i] - nums[j]);
            nums[i] = (char) (nums[i] - nums[j]);
            i++;
            j--;
        }

    }

}
